package presentation;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.Timer;

import control.CControl;

public class PSettingsForm extends JPanel {
	private static final long serialVersionUID = 1L;
	private CControl cControl;
	private PButton saveSettings,saveMapSettings;
	private String[] panelModeOptions = {"Tabbed","Separate"};
	private PComboBox panelModeChooser, mapChooser;
	private PTextField tllatField, tllongField, brlatField, brlongField;
	private PTextField mediumField, highField, veryHighField;
	private PTextField dataAddressField, dataPortField, webcamUrlField;
	private Timer saveTimer, saveMapTimer;
	private JLabel saved = new JLabel("",JLabel.CENTER);
	private JLabel mapSaved = new JLabel("",JLabel.CENTER);
	private final int SAVE_LABEL_VISIBLE = 1000;

	public PSettingsForm(CControl cControl) {
		this.cControl = cControl;
		this.setLayout(new GridLayout(11,4,30,10));
		this.setPreferredSize(new Dimension(800,352));
		this.setMaximumSize(new Dimension(800,352));
		this.setMinimumSize(new Dimension(800,352));
		this.setBackground(Color.white);
		
		Font headerFont = new Font("Arial",Font.BOLD,18);
		Font plainFont = new Font("Arial",Font.PLAIN,14);
		
		ButtonListener buttonListener = new ButtonListener();
		TimerListener timerListener = new TimerListener();
		
		saveTimer = new Timer(SAVE_LABEL_VISIBLE,timerListener);
		saveMapTimer = new Timer(SAVE_LABEL_VISIBLE,timerListener);
		
		saveSettings = new PButton("Save",buttonListener,plainFont);
		saveMapSettings = new PButton("Save",buttonListener,plainFont);
		
		panelModeChooser = new PComboBox(panelModeOptions,buttonListener,plainFont);
		mapChooser = new PComboBox(cControl.getMaps(),buttonListener,plainFont);
		
		tllatField = new PTextField("",plainFont);
		tllongField = new PTextField("",plainFont);
		brlatField = new PTextField("",plainFont);
		brlongField = new PTextField("",plainFont);
		
		mediumField = new PTextField("",plainFont);
		highField = new PTextField("",plainFont);
		veryHighField = new PTextField("",plainFont);
		
		dataAddressField = new PTextField("",plainFont);
		dataPortField = new PTextField("",plainFont);
		webcamUrlField = new PTextField("",plainFont);
		
		// Line 1
		JLabel connectionHeader = new JLabel("Connection:");
		connectionHeader.setFont(headerFont);
		this.add(connectionHeader);
		this.add(new JLabel());
		
		JLabel mapSettingsHeader = new JLabel("Map settings:");
		mapSettingsHeader.setFont(headerFont);
		this.add(mapSettingsHeader);
		this.add(new JLabel());
		
		// Line 2
		JLabel dataAddressLabel = new JLabel("Data address:");
		dataAddressLabel.setFont(plainFont);
		this.add(dataAddressLabel);
		this.add(dataAddressField);
		
		JLabel mapLabel = new JLabel("Map:");
		mapLabel.setFont(plainFont);
		this.add(mapLabel);
		this.add(mapChooser);
		
		// Line 3
		JLabel dataPortLabel = new JLabel("Data port:");
		dataPortLabel.setFont(plainFont);
		this.add(dataPortLabel);
		this.add(dataPortField);
		
		JLabel tlLatitudeLabel = new JLabel("Top left, latitude:");
		tlLatitudeLabel.setFont(plainFont);
		this.add(tlLatitudeLabel);
		this.add(tllatField);
		
		// Line 4
		JLabel webcamUrlLabel = new JLabel("Webcam url:");
		webcamUrlLabel.setFont(plainFont);
		this.add(webcamUrlLabel);
		this.add(webcamUrlField);
		
		JLabel tlLongitudeLabel = new JLabel("Top left, longitude:");
		tlLongitudeLabel.setFont(plainFont);
		this.add(tlLongitudeLabel);
		this.add(tllongField);
		
		// Line 5
		JLabel windowSettingsHeader = new JLabel("Window settings:");
		windowSettingsHeader.setFont(headerFont);
		this.add(windowSettingsHeader);
		this.add(new JLabel());
		
		JLabel brLatitudeLabel = new JLabel("Bottom right, latitude:");
		brLatitudeLabel.setFont(plainFont);
		this.add(brLatitudeLabel);
		this.add(brlatField);
		
		// Line 6
		JLabel panelLabel = new JLabel("Panel settings:");
		panelLabel.setFont(plainFont);
		this.add(panelLabel);
		this.add(panelModeChooser);
		
		JLabel brLongitudeLabel = new JLabel("Bottom right, longitude:");
		brLongitudeLabel.setFont(plainFont);
		this.add(brLongitudeLabel);
		this.add(brlongField);
		
		// Line 7
		JLabel tireSettingsHeader = new JLabel("Tire temp settings:");
		tireSettingsHeader.setFont(headerFont);
		this.add(tireSettingsHeader);
		this.add(new JLabel());
		
		mapSaved.setFont(plainFont);
		this.add(mapSaved);
		this.add(saveMapSettings);
		
		// Line 8
		JLabel mediumLabel = new JLabel("Medium, start:");
		mediumLabel.setFont(plainFont);
		this.add(mediumLabel);
		this.add(mediumField);
		
		this.add(new JLabel());
		this.add(new JLabel());
		
		// Line 9
		JLabel highLabel = new JLabel("High, start:");
		highLabel.setFont(plainFont);
		this.add(highLabel);
		this.add(highField);
		
		this.add(new JLabel());
		this.add(new JLabel());
		
		// Line 10
		JLabel veryHighLabel = new JLabel("Very high, start:");
		veryHighLabel.setFont(plainFont);
		this.add(veryHighLabel);
		this.add(veryHighField);
		
		this.add(new JLabel());
		this.add(new JLabel());
		
		// Line 11
		saved.setFont(plainFont);
		this.add(saved);
		this.add(saveSettings);
		
		this.add(new JLabel());
		this.add(new JLabel());
		
		// Initialize settings panel:
		initConnectionSettings();
		initWindowSettings();
		initTireTempSettings();
		initMapSettings();
	}
	
	
	
	private void initWindowSettings() {
		String panelSettings = cControl.getSettingsParameter("panelsettings");
		
		if (panelSettings == null) {
			panelSettings = "Tabbed";
		}
		
		panelModeChooser.setSelectedItem(panelSettings);
	}
	
	private void initConnectionSettings() {
		String dataAdress = cControl.getSettingsParameter("dataaddress");
		String dataPort = cControl.getSettingsParameter("dataport");
		String webcamUrl = cControl.getSettingsParameter("videourl");
		
		if (dataAdress == null) {
			dataAdress = "";
		}
		
		if (dataPort == null) {
			dataPort = "0";
		}
		
		if (webcamUrl == null) {
			webcamUrl = "";
		}
		
		dataAddressField.setText(dataAdress);
		dataPortField.setText(dataPort);
		webcamUrlField.setText(webcamUrl);
	}
	
	private void initMapSettings() {
		String map = "";
		if (mapChooser.getSelectedItem() != null) {
			map = mapChooser.getSelectedItem().toString();
			String[] splitMap = map.split("[.]");
			map = map.substring(0,map.length()-(splitMap[splitMap.length-1].length()+1));
			
			double tllat = 0, tllong = 0, brlat = 0, brlong = 0;
			
			try {
				tllat = Double.parseDouble(cControl.getSettingsParameter(map + "tllat"));
			} catch (Exception e) {}
			
			try {
				tllong = Double.parseDouble(cControl.getSettingsParameter(map + "tllong"));
			} catch (Exception e) {}
			
			try {
				brlat = Double.parseDouble(cControl.getSettingsParameter(map + "brlat"));
			} catch (Exception e) {}
			
			try {
				brlong = Double.parseDouble(cControl.getSettingsParameter(map + "brlong"));
			} catch (Exception e) {}
			
			tllatField.setText(tllat + "");
			tllongField.setText(tllong + "");
			brlatField.setText(brlat + "");
			brlongField.setText(brlong + "");
		}
	}
	
	private void initTireTempSettings() {
		int wtMedium = 0, wtHigh = 0, wtVeryHigh = 0;
		
		try {
			wtMedium = Integer.parseInt(cControl.getSettingsParameter("wheeltempmedium"));
		} catch (Exception e) {}
		
		try {
			wtHigh = Integer.parseInt(cControl.getSettingsParameter("wheeltemphigh"));
		} catch (Exception e) {}
		
		try {
			wtVeryHigh = Integer.parseInt(cControl.getSettingsParameter("wheeltempveryhigh"));
		} catch (Exception e) {}
		
		mediumField.setText(wtMedium + "");
		highField.setText(wtHigh + "");
		veryHighField.setText(wtVeryHigh + "");
	}
	
	private class ButtonListener implements ActionListener {

		@Override
		public void actionPerformed(ActionEvent e) {
			if (e.getSource() == saveSettings) {
				String panelMode = panelModeChooser.getSelectedItem().toString();
				String dataAdress = dataAddressField.getText();
				String webcamUrl = webcamUrlField.getText();
				try {
					int wtmedium = Integer.parseInt(mediumField.getText());
					int wthigh = Integer.parseInt(highField.getText());
					int wtveryhigh = Integer.parseInt(veryHighField.getText());
					int dataPort = Integer.parseInt(dataPortField.getText());
					
					if (cControl.setSettingsParameter("dataaddress",dataAdress) &&
					cControl.setSettingsParameter("dataport",dataPort + "") &&
					cControl.setSettingsParameter("videourl",webcamUrl) &&
					cControl.setSettingsParameter("wheeltempmedium", wtmedium + "") &&
					cControl.setSettingsParameter("wheeltemphigh", wthigh + "") &&
					cControl.setSettingsParameter("wheeltempveryhigh", wtveryhigh + "") &&
					cControl.setSettingsParameter("panelsettings", panelMode)) {
						saved.setText("Saved...");
						saved.setForeground(Color.black);
						saveTimer.start();
					} else {
						saved.setText("Unable to save...");
						saved.setForeground(Color.red);
						saveTimer.start();
					}
				} catch (Exception exc) {
					saved.setText("Values not supported.");
					saved.setForeground(Color.red);
					saveTimer.start();
				}
			} else if (e.getSource() == saveMapSettings) {
				String map = mapChooser.getSelectedItem().toString();
				String[] splitMap = map.split("[.]");
				map = map.substring(0,map.length()-(splitMap[splitMap.length-1].length()+1));
				try {
					double tllat = Double.parseDouble(tllatField.getText());
					double tllong = Double.parseDouble(tllongField.getText());
					double brlat = Double.parseDouble(brlatField.getText());
					double brlong = Double.parseDouble(brlongField.getText());
					
					if (cControl.setSettingsParameter(map + "tllat", tllat + "") && 
					cControl.setSettingsParameter(map + "tllong", tllong + "") && 
					cControl.setSettingsParameter(map + "brlat", brlat + "") && 
					cControl.setSettingsParameter(map + "brlong", brlong + "")) {
						mapSaved.setText("Saved...");
						mapSaved.setForeground(Color.black);
						saveMapTimer.start();
					} else {
						mapSaved.setText("Unable to save. Check log.");
						mapSaved.setForeground(Color.red);
						saveMapTimer.start();
					}
					
				} catch (Exception exc) {
					mapSaved.setText("Values not supported.");
					mapSaved.setForeground(Color.red);
					saveMapTimer.start();
				}
			} else if (e.getSource() == mapChooser) {
				initMapSettings();
			}
		}
	}
	
	private class TimerListener implements ActionListener {

		@Override
		public void actionPerformed(ActionEvent e) {
			if (e.getSource() == saveTimer) {
				saveTimer.stop();
				saved.setText("");
			} else if (e.getSource() == saveMapTimer) {
				saveMapTimer.stop();
				mapSaved.setText("");
			}
		}
	}
}
